package com.taotao.order.service.impl;

import com.alibaba.nacos.common.packagescan.resource.ClassPathResource;
import com.taotao.order.service.LuaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @className: LuaServiceImpl
 * @author: ZhangYuQi
 * @date: 2025/2/7 下午2:04
 * @Version: 1.0
 * @description:
 */

@Service
public class LuaServiceImpl implements LuaService {

    @Autowired
    private com.taotao.common.redis.service.RedisService redisService;

    /**
     * 尝试购买商品
     *
     * @param
     * @param  （默认为1）
     * @return true表示购买成功，false表示购买失败（库存不足）
     */
    public boolean tryToBuy(List<String> skuIds, List<Integer> buyQuantities) throws IOException {
        // 读取Lua脚本文件
        String luaScript = new String(new ClassPathResource("redis/PreventSkuOverselling.lua").getInputStream().readAllBytes(), StandardCharsets.UTF_8);

        List<String> skuInfoKeys =new ArrayList<>();

        // 构造Redis键
        skuIds.forEach(skuId -> {
            String skuKey = "skuInfo:" + skuId;
            skuInfoKeys.add(skuKey);
        });


        // 将Lua脚本封装为DefaultRedisScript对象
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setScriptText(luaScript);
        script.setResultType(Long.class);
        RedisTemplate<String,Object> redisTemplate = redisService.redisTemplate;
        // 执行Lua脚本
        Long result = redisTemplate.execute(script, skuInfoKeys, buyQuantities.toArray());

        // 判断返回结果
        if (result == 0) {
            // 处理失败
           // List<String> failedSkus = (List<String>) result.get(1);
            //System.out.println("扣减失败 因为以下sku购买数量超过库存数量" + failedSkus);
            return false;
        } else {
            return true;
        }


    }
}
